package web.api.global.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import web.api.global.message.ErrorResponse;

import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2022-01-25
 */
@Configuration
public class OpenApiConfig {
	private String description = "Web演示";

	public OpenApiConfig() {
	}

	@Bean
	public OpenAPI openAPI() {
		Components components = new Components();
		populateCommonResponse(components);

		return new OpenAPI()
				.info(new Info().title("Web演示")
						.description(description)
						.version("1.0.0")
						.license(new License().name("Apache 2.0").url("http://springdoc.org")))
				.servers(List.of(new Server().url("http://localhost:8080")))
				.components(components.addSecuritySchemes("basicScheme",
						new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic")));
	}

	private void populateCommonResponse(Components components) {
		ApiResponse response200 = new ApiResponse();
		response200.setDescription("OK");
		components.addResponses("response200", response200);

		ApiResponse response400 = new ApiResponse();
		response400.setDescription("Bad Request");
		response400.setContent(new Content().addMediaType("application/json", new MediaType()
				.schema(new Schema<ErrorResponse>()
						.example(new ErrorResponse(400_000_000, "Bad Request")))));
		components.addResponses("response400", response400);

		ApiResponse response401 = new ApiResponse();
		response401.setDescription("Unauthorized");
		components.addResponses("response401", response401);

		ApiResponse response404 = new ApiResponse();
		response404.setDescription("The specified resource was not found");
		components.addResponses("response404", response404);

		ApiResponse response500 = new ApiResponse();
		response500.setDescription("Internal Server Error");
		response500.setContent(new Content().addMediaType("application/json", new MediaType()
				.schema(new Schema<ErrorResponse>()
						.example(new ErrorResponse(500_000_000, "Internal Server Error")))));
		components.addResponses("response500", response500);
	}

}
